package com.rxjava.test.rxjava;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Function;

import java.net.URI;
import java.util.Collections;
import java.util.List;

public class CatsHelper {
    ApiWrapper apiWrapper;


    public Observable<URI> saveTheCutesCat(String query) {
        Observable<List<Cat>> catsListObservable = apiWrapper.queryCats(query);

        Observable<Cat> cutestCatObservable = catsListObservable.map(new Function<List<Cat>, Cat>() {
            @Override
            public Cat apply(List<Cat> cats) throws Throwable {
                return findCutest(cats);
            }
        });

        Observable<URI> uriObservable = cutestCatObservable.flatMap(new Function<Cat, ObservableSource<URI>>() {
            @Override
            public ObservableSource<URI> apply(Cat cat) throws Throwable {
                return apiWrapper.store(cat);
            }
        });
        return uriObservable;
    }

    private Cat findCutest(List<Cat> cats) {
        return Collections.max(cats);
    }
}
